﻿using System;
using System.IO;
using System.Linq;
using EnvDTE;

namespace SmartStringResources.Dte
{
	public static class ProjectItemsExtensions
	{
		public static ProjectItem GetProjectItemByFullPath(this ProjectItems projectItems, string fullPath)
		{
			var enumerable = projectItems.OfType<ProjectItem>().Where(d => d.FileCount > 0).Select(pi => new
				{
					ProjectItem = pi,
					FullPath = Enumerable.Range(1, pi.FileCount).Select(i => pi.FileNames[(short)(i - 1)]).FirstOrDefault(fullPath.StartsWith)
				});
			var projectItem = enumerable
				.FirstOrDefault(pi => pi.FullPath != null);

			if (projectItem == null)
				return null;

			if (projectItem.FullPath == fullPath)
				return projectItem.ProjectItem;

			return projectItem.ProjectItem.ProjectItems.GetProjectItemByFullPath(fullPath);
		}
	}
}
